#include"LinkQueue.h"

void Init_LinkQueue(LinkQueue* plq)
{
	assert(plq);

	plq->front = plq->rear = NULL;
	
}

LQNode* Buy_LQNode(ELEMTYPE val)
{
	LQNode* newnode = (LQNode*)malloc(sizeof(LQNode));
	if (!newnode)
		exit(EXIT_FAILURE);

	newnode->data = val;
	newnode->next = NULL;

	return newnode;
}

bool Push(LinkQueue* plq, ELEMTYPE val)
{
	assert(plq);

	LQNode* newnode = Buy_LQNode(val);

	if (Empty(plq))
		plq->front = plq->rear = newnode;
	else
	{
		plq->rear->next = newnode;
		plq->rear = newnode;
	}

	return true;
}

bool Pop(LinkQueue* plq)
{
	assert(plq);

	if (Empty(plq))
		return false;

	if (Size(plq) == 1)
		plq->rear = NULL;

	LQNode* del = plq->front;
	plq->front = del->next;
	free(del);
	del = NULL;

	return true;
}

ELEMTYPE Front(LinkQueue* plq)
{
	assert(plq);

	if (Empty(plq))
		exit(EXIT_FAILURE);

	return plq->front->data;
}

int Size(LinkQueue* plq)
{
	assert(plq);

	int cnt = 0;

	for (LQNode* pcur = plq->front; pcur; cnt++, pcur = pcur->next);

	return cnt;
}

bool Empty(LinkQueue* plq)
{
	assert(plq);

	return plq->front == NULL;
}

void Destroy(LinkQueue* plq)
{
	assert(plq);
	
	LQNode* del = plq->front;
	LQNode* next = NULL;
	
	while (del)
	{
		next = del->next;
		free(del);
		del = next;
	}

	plq->front = plq->rear = NULL;
}

void Show(LinkQueue* plq)
{
	assert(plq);

	for (LQNode* pcur = plq->front; pcur; pcur = pcur->next)
		printf("%d -> ", pcur->data);
	printf("NULL\n");
}

int main()
{
	LinkQueue q;

	Init_LinkQueue(&q);
	Show(&q);

	Push(&q, 1);
	Push(&q, 2);
	Push(&q, 3);
	Push(&q, 4);
	Push(&q, 5);
	Show(&q);
	printf("%d\n", Size(&q));

	Pop(&q);
	Pop(&q);
	Show(&q);

	printf("%d\n", Front(&q));
	printf("%d\n", Size(&q));

	Destroy(&q);
	Show(&q);
	printf("%d\n", Size(&q));

	return 0;
}

